package com.qianbei.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBindBean;
import com.qianbei.bean.GetBindBean1;
import com.qianbei.bean.GetBindBean2;
import com.qianbei.bean.GetBoxBody;
import com.qianbei.bean.GetBoxBody1;
import com.qianbei.bean.GetCarbean2;
import com.qianbei.bean.GetUpbox;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.adapter.ScanAdapter;
import com.qianbei.view.db.Box;
import com.qianbei.view.db.BoxDb;

import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.util.JobBoxUtil;
import com.qianbei.view.util.MessageCallback;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.UHFManager;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;


/**
 * Created by gaoml on 2018/1/17.
 */

public class BoxUPActivity extends BaseActivity {

    @Bind(R.id.scan_stat_info)
    TextView scanStat;

    @Bind(R.id.finish_scan)
    TextView finishButton;

    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;


    private IUHFService iuhfService;
    private ListView EpcList;
    private TextView Status;
    private List<EpcDataBase> firm = new ArrayList<EpcDataBase>();

    private ScanAdapter adapter;

    private Set<String> alreadySave = new HashSet<String>();
    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);
    /**
     * 成功上电
     */
    private AtomicBoolean isOpenSucces = new AtomicBoolean(false);
    private RFIDDao rfidDao;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    private AtomicBoolean canRead = new AtomicBoolean(false);
    private BoxDb boxDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_boxup_activity);

        ButterKnife.bind(this);

        EpcList = (ListView) findViewById(R.id.listView_search_epclist);
        Status = (TextView) findViewById(R.id.textView_search_status);

        adapter = new ScanAdapter(
                this, firm, R.layout.gufei_item_scan);
        EpcList.setAdapter(adapter);

        adapter.setStatus(Status);
        adapter.setStat(scanStat);
        adapter.setDelCallback(new MessageCallback(){
            @Override
            public void call() {
                updateStatus();
            }
        });

        boxDb = new BoxDb(this);

        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.scan_stat).setVisibility(View.GONE);

        setTitle("周转箱装卸");
        mTitle.setrightTitle("完成扫描");
        if (TextUtils.isEmpty(SetData.getCarId())) {
            startActivity(GetCarActivity.class);
            new MsgAlert().show("请先绑定车辆");
            finish();
        }

        iuhfService = MyApplication.iuhfService;

        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {
                handler.sendMessageDelayed(handler.obtainMessage(111, var1), 1000);
            }
        });

        newWakeLock();

        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        rfidDao = daoSession.getRFIDDao();
    }


    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }

    boolean ishow = false;
    EpcDataBase b;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    final SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var1.epc);

//                    if(firm.size()>0){
//                        for (int i =0 ;i<firm.size();i++) {
//                             b  = firm.get(i);
//                            Log.d("gaoaaa","b.epc"+b.epc);
//                            Log.d("gaoaaa","J====="+var1.epc);
//                            if (!b.epc.equals(var1.epc)){
//                                firm.add(new EpcDataBase(var1.epc, 1,
//                                        var1.rssi, var1.tid));
//                            }
//
//                        }
//                    }else if(firm.size()==0){
//                        firm.add(new EpcDataBase(var1.epc, 1,
//                                var1.rssi, var1.tid));
//                    }


                    int j;
                    for (j = 0; j < firm.size(); j++) {
                        if (var1.epc.equals(firm.get(j).epc)) {
                            firm.get(j).valid++;
                            firm.get(j).setRssi(var1.rssi);
                            break;
                        }
                    }
                    if (j == firm.size()) {


                        final EpcDataBase epcDataBase = new EpcDataBase(var1.epc, 1,
                                var1.rssi, var1.tid);


                        if (canRead.getAndSet(false)) {
                            firm.clear();
                            ring();
                            mTitle.setrightTitle("完成扫描");
                            iuhfService.newInventoryStop();

                            JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                                @Override
                                public void call() {

                                    QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                                    qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.Rfid.eq(var1.epc), RFIDDao.Properties.WhichStep.eq("nullBoxLoad")));

                                    List<RFID> queryRfid = qb.list();
                                    if (TextUtils.isEmpty(epcDataBase.boxId)) {
                                        new MsgAlert().show("rfid与箱号未绑定");
                                        return;
                                    }
                                    if (queryRfid.size() == 0) {

                                        RFID rfid = new RFID();
                                        rfid.setRfid(var1.epc);
                                        rfid.setBoxNum(epcDataBase.boxId);
                                        rfid.setBoxType(epcDataBase.boxType);
                                        if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                            rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                        }
                                        rfid.setJobId(SetData.getJobid());
                                        rfid.setWhichStep("nullBoxLoad");

                                        rfidDao.save(rfid);

                                    }else {

                                        RFID rfid = queryRfid.get(0);
                                        rfid.setBoxNum(epcDataBase.boxId);
                                        rfid.setBoxType(epcDataBase.boxType);
                                        if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                            rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                        }
                                        rfidDao.update(rfid);

                                    }
                                    firm.clear();
                                    firm.add(0, epcDataBase);
                                    adapter.notifyDataSetChanged();
                                    updateStatus();

                                }
                            });

                        }


                    }


                    break;

                case 2:
                    mTitle.setrightTitle("完成扫描");
                    iuhfService.newInventoryStop();
                    break;
            }

        }
    };

    private void ring() {


        Uri notification = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.beep_once);
        if (notification == null) return;
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    private void vibrate(){
        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                    if (iuhfService != null) {
                        iuhfService.newInventoryStop();
                    }

                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        mTitle.setrightTitle("完成扫描");
        isOpenDev.set(false);

        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {
                handler.sendMessageDelayed(handler.obtainMessage(111, var1), 1000);
            }
        });


        if (firm != null && firm.size() > 0) {
            for (final EpcDataBase epcDataBase : firm) {
                JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                    @Override
                    public void call() {

                        QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                        qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.Rfid.eq(epcDataBase.epc), RFIDDao.Properties.WhichStep.eq("nullBoxLoad")));
                        if (!TextUtils.isEmpty(epcDataBase.boxId)) {
                            List<RFID> queryRfid = qb.list();
                            if (queryRfid.size() == 1) {
                                RFID rfid = queryRfid.get(0);
                                rfid.setBoxNum(epcDataBase.boxId);
                                rfid.setBoxType(epcDataBase.boxType);
                                if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                    rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                }
                                rfidDao.update(rfid);
                            }
                        }

                    }
                });
            }

            Collections.sort(firm);
        }



        updateStatus();
        adapter.notifyDataSetChanged();


    }

    /**
     * 更新扫描大小箱计数
     */
    private void updateStatus() {
        try {
            if(!TextUtils.isEmpty(SetData.getJobid())){
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("nullBoxLoad")));
                List<RFID> queryRfid = qb.list();

                JobBoxUtil util = new JobBoxUtil();
                String count = util.countBox(queryRfid, false);
                Status.setText(count);
                scanStat.setText(count);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Dispatch incoming result to the correct fragment.
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0 && data != null) {


        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                finishScan(findViewById(R.id.tv_right));
                break;
            default:
                break;
        }

    }

    @OnTouch(R.id.finish_scan)
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d("touchEven", "down");
                Log.d("fClick:", isOpenDev.get() + "");
                vibrate();
                finishButton.setBackgroundColor(getResources().getColor(R.color.color_4d9dce));
                mTitle.setrightTitle("扫描中...");
                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (openDev()) {
                                    isOpenDev.set(false);
                                    return null;
                                } else {
                                    isOpenSucces.set(true);
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }
                            iuhfService.newInventoryStart();
                            canRead.set(true);

                            return null;
                        }
                    }.execute();

                } else if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStart();
                    canRead.set(true);

                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d("touchEven", "up");
                finishButton.setBackgroundColor(getResources().getColor(R.color.color_519DCC));
                mTitle.setrightTitle("完成扫描");
                if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStop();
                } else {
                    delayStop();
                }
                break;
            default:
                break;
        }
        return true;
    }

    private void delayStop() {

        handler.sendEmptyMessageDelayed(2, 5000);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.save:
                if (firm.size() > 0) {
                    confirmFinish();
                }

                break;

            default:
                break;
        }
    }

    public void confirmFinish() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("确认保存吗？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updateLoad();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    public void finishScan(View view) {
        findViewById(R.id.scan_stat).setVisibility(View.VISIBLE);
        findViewById(R.id.save).setVisibility(View.VISIBLE);
        findViewById(R.id.finish_scan).setVisibility(View.GONE);


        if (!TextUtils.isEmpty(SetData.getJobid())) {
            Log.d("JobSavedRFID", SetData.getJobid());
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.WhichStep.eq("nullBoxLoad"), RFIDDao.Properties.JobId.eq(SetData.getJobid())));
            qb.orderAsc(RFIDDao.Properties.Id);

            List<RFID> queryRfid = qb.list();
            if (queryRfid.size() > 0) {
                for (RFID rfid : queryRfid) {
                    EpcDataBase epcDataBase = new EpcDataBase(rfid.getRfid(), 1,
                            "", "");
                    epcDataBase.setBoxId(rfid.getBoxNum());
                    epcDataBase.setBoxType(rfid.getBoxType());
                    epcDataBase.setTypeValue(rfid.getBoxTypeIntVal() + "");

                    if (!firm.contains(epcDataBase)) {
                        firm.add(epcDataBase);
                    }
                }

            }
        }


        Collections.sort(firm);

        adapter.notifyDataSetChanged();
        adapter.updateStatusText(false);
        adapter.updateStat();


    }


//    class EpcDataBase {
//        public String epc;
//        int valid;
//        String rssi;
//        String tid_user;
//
//        public EpcDataBase(String e, int v, String rssi, String tid_user) {
//            // TODO Auto-generated constructor stub
//            epc = e;
//            valid = v;
//            this.rssi = rssi;
//            this.tid_user = tid_user;
//        }
//
//        public String getRssi() {
//            return rssi;
//        }
//
//        public void setRssi(String rssi) {
//            this.rssi = rssi;
//        }
//
//        @Override
//        public String toString() {
//            if (TextUtils.isEmpty(tid_user)) {
//                return "EPC:" + epc + "\n"
//                        + "(" + "COUNT:" + valid + ")" + " RSSI:" + rssi + "\n";
//            } else {
//                return "EPC:" + epc + "\n"
//                        + "T/U:" + tid_user + "\n"
//                        + "(" + "COUNT:" + valid + ")" + " RSSI:" + rssi + "\n";
//            }
//        }
//
//    }


    /**
     * 绑定  车辆和 人
     */
    private void updateLoad() {
        ArrayList<String> where = new ArrayList<>();
        for (EpcDataBase a : firm) {
            where.add(a.epc);
        }
        RequeastBean bean = new RequeastBean("load", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                new GetUpbox(new GetBoxBody1(where), new GetBoxBody()));
        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean); bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetUpbox.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            iuhfService.newInventoryStop();
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        iuhfService.newInventoryStop();
                        new MsgAlert().show("保存成功");
                        finish();
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }


    }


}
